<template>
  <div>
    <el-card class="main-card">
      <el-row>
        <el-col :span="9">
          <el-input
            placeholder="请输入角色关键字"
            clearable
            v-model="queryInfo.queryString"
            @clear="findPage"
          >
            <el-button
              slot="append"
              icon="el-icon-search"
              @click="findPage"
            ></el-button>
          </el-input>
        </el-col>
        <el-col :span="2">
          <el-button
            @click="insert"
            style="margin-left: 10px"
            v-has-permission="['PER_ROLE_INSERT']"
            type="primary"
            >添加角色</el-button
          >
        </el-col>
      </el-row>
      <el-table
        :data="tableList"
        stripe
        border
        highlight-current-row
        v-loading="loading"
        element-loading-text="拼命加载中"
        element-loading-spinner="el-icon-loading"
        max-height="450"
      >
        <el-table-column type="index" label="序号"> </el-table-column>
        <el-table-column prop="label" label="角色名称"> </el-table-column>
        <el-table-column prop="value" label="角色标签值"> </el-table-column>
        <el-table-column
          label="启用状态"
          v-has-permission="['PER_ROLE_UPDATE']"
        >
          <template slot-scope="scope">
            <el-switch
              @change="updateStatus(scope.row)"
              v-model="scope.row.status"
            >
            </el-switch>
          </template>
        </el-table-column>
        <el-table-column fixed="right" label="操作" width="120">
          <template slot-scope="scope">
            <el-button
              @click="updateById(scope.row)"
              v-has-permission="['MENU_UPDATE']"
              type="primary"
              icon="el-icon-edit"
              size="small"
            ></el-button>
            <el-button
              type="danger"
              @click="deleteById(scope.row.id)"
              v-has-permission="['MENU_DELETE']"
              icon="el-icon-delete"
              size="small"
            ></el-button>
          </template>
        </el-table-column>
      </el-table>
      <div class="block">
        <el-pagination
          @size-change="handlePageSize"
          @current-change="handlePageNumber"
          background
          :current-page="queryInfo.pageNumber"
          :page-sizes="[8, 16, 32, 64, 128]"
          :page-size="queryInfo.pageSize"
          layout="total, sizes, prev, pager, next, jumper"
          :total="total"
        >
        </el-pagination>
      </div>
    </el-card>
    <!-- 表单添加/修改 -->
    <el-dialog
      :title="title"
      :visible.sync="open"
      @close="dialogClose"
      width="40%"
    >
      <el-form
        :model="form"
        :rules="rules"
        ref="form"
        label-position="right"
        label-width="120px"
      >
        <el-row>
          <el-card shadow="hover">
            <el-col :span="12">
              <el-form-item label="角色标签名称" prop="label">
                <el-input v-model="form.label" />
              </el-form-item>
            </el-col>
            <el-col :span="12">
              <el-form-item label="角色标签值" prop="value">
                <el-input v-model="form.value" />
              </el-form-item>
            </el-col>
          </el-card>
        </el-row>
        <el-row>
          <el-col :span="24">
            <el-card shadow="hover">
              <div slot="header">
                <span>菜单集合</span>
              </div>
              <el-tree
                :data="menuList"
                highlight-current
                :check-strictly="true"
                ref="tree"
                show-checkbox
                node-key="id"
                :props="defaultProps"
                @check-change="getTree"
              >
              </el-tree>
            </el-card>
          </el-col>
          <el-col :span="24">
            <el-card shadow="hover" class="permissions-class">
              <div slot="header">
                <span>权限集合</span>
              </div>
              <el-checkbox-group v-model="checkedPermissions">
                <el-checkbox
                  v-for="(item, index) in permissionList"
                  border
                  class="permissions-class1"
                  size="small"
                  :disabled="!item.status"
                  :label="item.label"
                  :key="index"
                  @change="permissionChange(item)"
                />
              </el-checkbox-group>
            </el-card>
          </el-col>
        </el-row>

        <el-form-item label="是否启用" prop="status">
          <el-radio-group v-model="form.status" class="status-class">
            <el-radio border :label="true">是</el-radio>
            <el-radio border :label="false">否</el-radio>
          </el-radio-group>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click="clickCancel">取 消</el-button>
        <el-button type="primary" @click="clickOk">确 定</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
export default {
  data() {
    return {
      // 分页查询条件
      queryInfo: {
        // 页码
        pageNumber: 1,
        // 页数
        pageSize: 8,
        // 关键字
        queryString: null,
        // 表格数据
      },
      tableList: [],
      // 总记录数
      total: 0,
      // 表单标题
      title: null,
      // 是否打开对话框
      open: false,
      // 表格加载
      loading: false,
      // 表单数据
      form: {
        status: true,
      },
      // 表单校验规则
      rules: {
        label: [
          { required: true, message: "请输入角色名称", trigger: "blur" },
          {
            min: 1,
            max: 100,
            message: "角色名称的长在1 ~ 50 个字符",
            trigger: "blur",
          },
        ],
        value: [
          { required: true, message: "请输入角色标签值", trigger: "blur" },
          {
            min: 1,
            max: 100,
            message: "角色标签值的长在1 ~ 50 个字符",
            trigger: "blur",
          },
        ],
      },

      // 菜单集合
      menuList: [],
      // 权限集合
      permissionList: [],

      // label 指定节点标签为节点对象的某个属性值,children 指定子树为节点对象的某个属性值
      defaultProps: {
        children: "children",
        label: "title",
      },
      // 选定的集合
      checkedPermissions: [],
      // 选定的菜单集合
      checkedMenuList: [],
      upPermission: [],
    };
  },

  created() {
    this.findPage();
    this.findMenus();
    this.findPermissions();
  },

  methods: {
    /** 分页查询 */
    findPage() {
      this.loading = true;
      this.$ajax.post("/role/findPage", this.queryInfo).then((res) => {
        this.loading = false;
        console.log("角色信息", res);
        this.tableList = res.data.rows;
        this.total = res.data.total;
      });
    },
    /** 页面大小改变事件 */
    handlePageSize(newPageSize) {
      this.queryInfo.pageSize = newPageSize;
      this.findPage();
    },
    /** 页面改变事件 */
    handlePageNumber(newPageNumber) {
      // 将分页参数新数据传递给pageNumber(分页参数)
      this.queryInfo.pageNumber = newPageNumber;
      this.findPage();
    },
    /** 新增角色信息 */
    insert() {
      this.title = "新增角色";
      this.open = true;
    },
    /** 修改角色信息 */
    updateById(row) {
      console.log("row", row);
      // 清空checkedMenuList checkedPermissions 防止数据重复
      this.checkedMenuList = [];
      this.checkedPermissions = [];
      this.title = "修改角色";
      this.form = row;
      // 遍历父级菜单信息 回显菜单
      row.sysMenus.forEach((item) => {
        this.checkedMenuList.push(item);
        // 遍历子集菜单信息
        if (item.children && item.children.length > 0) {
          item.children.forEach((i) => {
            this.checkedMenuList.push(i);
          });
        }
      });
      // 添加异步方法
      this.$nextTick(() => {
        this.$refs.tree.setCheckedNodes(this.checkedMenuList);
      });
      // 这里回显菜单信息 需要异步方法 ---直接使用，这里报错this.$refs.tree.setCheckedNodes(this.checkedMenuList);

      //  遍历权限集合 回显
      row.sysPermissions.forEach((item) => {
        this.checkedPermissions.push(item.label);
        this.upPermission.push(item);
      });
      this.open = true;
    },
    /** 删除角色信息 */
    deleteById(id) {
      this.$confirm(
        "您的操作将永久删除编号为{" + id + "}的数据, 是否继续?",
        "提示",
        {
          confirmButtonText: "确定",
          cancelButtonText: "取消",
          type: "warning",
        }
      )
        .then(() => {
          // 调后台退出接口
          this.$ajax.delete(`/role/delete/${id}`).then((res) => {
            this.$message.success(res.data.message);
            this.queryInfo.pageNumber = 1;
            this.findPage();
          });
        })
        .catch(() => {
          this.$message({
            type: "info",
            message: "已取消",
          });
        });
    },
    /** 关闭对话框事件 */
    dialogClose() {
      // 将表单进行重置，并移除校验效果
      this.$refs.form.resetFields();
      this.checkedPermissions = [];
      this.checkedMenuList = [];
      this.$refs.tree.setCheckedKeys([]);
      this.findPage();
    },
    /** 点击取消 */
    clickCancel() {
      this.checkedPermissions = [];
      this.$refs.tree.setCheckedKeys([]);
      this.checkedMenuList = [];
      this.form = {};
      this.open = false;
      this.findPage();
    },
    /** 点击确定 */
    clickOk() {
      // 进行表单校验
      this.$refs.form.validate((valid) => {
        // 校验不通过
        if (!valid) {
          return this.$message.error("表单校验失败,请检查后提交！");
        }
        // 将菜单、权限赋值给表单
        this.form.sysMenus = this.checkedMenuList;
        this.form.sysPermissions = this.upPermission;
        console.log("form", this.form);
        // 校验通过
        if (this.form.id === undefined || this.form.id === null) {
          this.$ajax.post("/role/insert/", this.form).then((res) => {
            console.log("添加表单数据", this.form);
            this.$message.success(res.data.message);
            this.open = false;
            this.findPage();
          });
        } else {
          this.$ajax.put("/role/update/", this.form).then((res) => {
            console.log("修改表单数据", this.form);
            this.$message.success(res.data.message);
            this.open = false;
            this.findPage();
          });
        }
      });
    },
    /** 改变菜单状态 */
    updateStatus(row) {
      this.$ajax
        .put("/role/update/", row)
        .then((res) => {
          this.$message.success("状态更新成功!");
        })
        .catch(() => {});
    },
    /** 查询菜单列表 */
    findMenus() {
      this.$ajax.get("/menu/findParent").then((res) => {
        this.menuList = res.data.data;
        // 改造父级菜单属性  添加不可选中属性
        this.menuList.filter((item) => {
          item.disabled = !item.status;
          // 改造子菜单信息
          if (item.children && item.children.length > 0) {
            item.children.filter((i) => {
              i.disabled = !i.status;
            });
          }
          return true;
        });
      });
    },
    /** 查询权限列表 */
    findPermissions() {
      this.$ajax.get("/Permission/findAll").then((res) => {
        this.permissionList = res.data.data;
      });
    },
    /** 获取tree选中数据 */
    getTree() {
      // 防止重复获取数据
      this.checkedMenuList = [];
      /**
       * getCheckedNodes： 若节点可被选择（即 show-checkbox 为 true），则返回目前被选中的节点所组成的数组
       * 1. 是否只是叶子节点，默认值为 false 2. 是否包含半选节点，默认值为 false
       * @type {D[] | [] | [*] | [*] | [*] | *}
       */
      const check = this.$refs.tree.getCheckedNodes(false, false);
      check.forEach((item) => {
        this.checkedMenuList.push(item);
      });
    },
    /** 勾选权限的事件 */
    permissionChange(item) {
      // 点击为勾选状态就添加到upPermission【】
      console.log("传入的权限", item);
      if (event.target.checked) {
        this.upPermission.push(item);
      } else {
        for (let i = 0; i < this.upPermission.length; i++) {
          if (this.upPermission[i].id === item.id) {
            this.upPermission.splice(i, 1);
          }
        }
      }
      console.log("勾选的权限", this.upPermission);
    },
  },
};
</script>

<style scoped>
.status-class {
  margin-left: -30%;
}
.permissions-class {
  text-align: left;
}
.permissions-class1 {
  margin: 5px;
}
</style>
